package com.techysky.service;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
@Component("cacheUtil")
public class  CacheUtil {

	public static final Map<String, Map<String, String>> loginCacheMap = new HashMap<String, Map<String, String>>();
	
	public static final Map<String, Integer> adminCacheMap = new HashMap<String, Integer>();

	/**
	 * Admin登录失败 登录记录到缓存
	 * 
	 * @param name
	 * @return
	 */
	public static void  writeAdminLoginCache() {
		if (null == adminCacheMap.get("loginCount")) {
			adminCacheMap.put("loginCount", 1);
		}
		adminCacheMap.put("loginCount", adminCacheMap.get("loginCount")+1);
	}
	
	public static void writeUserLoginCache(String name) {
		Map<String, String> map = loginCacheMap.get(name);
		if (null == map) {
			// 第一次登录失败
			map = new HashMap<>();
			map.put("loginCount", Integer.toString(1));
			String loginTime=DateUtil.nowDate();
			map.put("firstLoginTime", loginTime);
		}
		
		map.put("loginCount", Long.toString(Long.parseLong(map.get("loginCount"))+1));
		loginCacheMap.put(name, map);
	}
	
	

	// 检查状态，返回true，检查通过可以继续登录 ，false不能登录 管理员上
	public static boolean checkStatus(String name) {
		if (!StringUtils.isEmpty(name)) {
			if (null != loginCacheMap.get(name)) {
				Map<String, String> map = loginCacheMap.get(name);
				long firstFailureDate = DateUtil.fromDateStringToLong(map.get("firstLoginTime"));
				long nowDate = DateUtil.fromDateStringToLong(DateUtil.nowDate());
			    long  count=Long.parseLong(map.get("loginCount"));
				if (DateUtil.timeCalculation(nowDate, firstFailureDate) < 10) {// 小于10分钟
					if(count < 5){
						writeUserLoginCache(name);
						return true;
					}else{
						return false;
					}
				} else {
					clearLoginCache(name);
					return false;
				}
	      	}else{
	      		writeUserLoginCache(name);
	      	}
	    }
		return true;
	}
	// 清登记录
	public static void clearAdminCache() {
			adminCacheMap.clear();
	}
	
	// 清登记录
	public static void clearLoginCache(String name) {
		if (!StringUtils.isEmpty(name)) {
			loginCacheMap.remove(name);
		}else{
			loginCacheMap.clear();
		}
	}
	public static boolean check(String name) {
		if (!StringUtils.isEmpty(name)) {
			if (null != loginCacheMap.get(name)) {
				Map<String, String> map = loginCacheMap.get(name);
				long firstFailureDate = DateUtil.fromDateStringToLong(map.get("firstLoginTime"));
				long nowDate = DateUtil.fromDateStringToLong(DateUtil.nowDate());
			    long  count=Long.parseLong(map.get("loginCount"));
				if (DateUtil.timeCalculation(nowDate, firstFailureDate) < 10) {// 小于10分钟
					if(count < 5){
						return true;
					}else{
						return false;
					}
				} else {
					clearLoginCache(name);
					return false;
				}
	      	}
	    }
		return true;
	}

}